package handlers

import (
	"errors"
	"github.com/869413421/wechatbot/config"
	"github.com/869413421/wechatbot/gtp"
	"github.com/eatmoreapple/openwechat"
	"log"
	"strings"
)

var _ MessageHandlerInterface = (*UserMessageHandler)(nil)

const enableChatGPT = "@解锁ChatGPT"  // 解锁 chatGPT 聊天模式口令
const disableChatGPT = "@退出ChatGPT" // 退出 chatGPT 聊天模式口令

var usersMap map[string]string = make(map[string]string)

// UserMessageHandler 私聊消息处理
type UserMessageHandler struct {
}

// handle 处理消息，目前只处理文本消息
func (g *UserMessageHandler) handle(msg *openwechat.Message) error {
	sender, err := msg.Sender()
	if err != nil {
		return nil
	}

	// 解锁 chatGPT 聊天模式
	if msg.Content == enableChatGPT {
		usersMap[sender.ID()] = sender.ID()
		_, err := msg.ReplyText("已经切换成 ChatGPT 对话模式")
		return err
	} else if msg.Content == disableChatGPT { // 退出 chatGPT 聊天模式
		delete(usersMap, sender.ID())
		_, err := msg.ReplyText("您已经退出 ChatGPT 对话模式")
		return err
	}

	// 只使用 chatGPT 回复白名单用户
	_, ok := usersMap[sender.ID()]
	if msg.IsText() && ok {
		return g.ReplyText(msg)
	}
	return nil
}

// NewUserMessageHandler 创建私聊处理器
func NewUserMessageHandler() MessageHandlerInterface {
	return &UserMessageHandler{}
}

// ReplyText 发送文本消息到群
func (g *UserMessageHandler) ReplyText(msg *openwechat.Message) error {
	// 接收私聊消息
	sender, err := msg.Sender()
	log.Printf("Received User %v Text Msg : %v", sender.NickName, msg.Content)
	if UserService.ClearUserSessionContext(sender.ID(), msg.Content) {
		_, err = msg.ReplyText("上下文已经清空了，你可以问下一个问题啦。")
		if err != nil {
			log.Printf("response user error: %v \n", err)
		}
		return nil
	}

	// 获取上下文，向GPT发起请求
	requestText := strings.TrimSpace(msg.Content)
	requestText = strings.Trim(msg.Content, "\n")

	requestText = UserService.GetUserSessionContext(sender.ID()) + requestText
	var reply string
	var retryCount = 3 // 重试次数
	err = errors.New("")
	for err != nil {
		reply, err = gtp.Completions(requestText)
		retryCount--
		if retryCount < 0 {
			break
		}
	}

	if err != nil {
		log.Printf("gtp request error: %v, retry .... \n", err)
		_, _ = msg.ReplyText(config.LoadConfig().ErrorText)
		return err
	}

	if reply == "" {
		return nil
	}

	// 设置上下文，回复用户
	reply = strings.TrimSpace(reply)
	reply = strings.Trim(reply, "\n")
	UserService.SetUserSessionContext(sender.ID(), requestText, reply)
	// 加上回复前缀
	replyPrefix := config.LoadConfig().ReplyPrefix
	if replyPrefix != "" {
		reply = replyPrefix + reply
	}
	_, err = msg.ReplyText(reply)
	if err != nil {
		log.Printf("response user error: %v \n", err)
	}
	return err
}
